classdef SystemMonitor < handle
    properties
        record
    end
    properties(Access = private)
        system
        timerObj = []
    end
    
    %% Singleton Implementation
    methods (Static)
        function obj = getMonitor()
            persistent localObj;
            if isempty(localObj) || ~isvalid(localObj)
                localObj = Table1.SystemMonitor();
            end
            obj = localObj;
        end
    end
    
    methods (Access = private)
        function obj = SystemMonitor()
            L=log4m.getLogger;
            L.info('SystemMonitor::SystemMonitor', 'A new SystemMonitor object is created.');
            obj.record=struct([]);
            obj.createTimer();
        end
    end
    
    methods
        function delete(obj)
            delete(timerfind('Name', 'MonitorTimer'));
            fprintf('SystemMonitor::delete\t The SystemMonitor [started at %s] object is deleted from memory.\n',  datestr(obj.start_time));
        end
        
        function obj = setSystem(obj, sys)
            obj.system = sys;
        end
        
        function getData(obj)
            r.timestamp = datetime('now');
            [r.pumpFrequency.value,   r.pumpFrequency.timestamp] = obj.system.getPumpFrequency();
            [r.probeFrequency.value,  r.probeFrequency.timestamp] = obj.system.getProbeFrequency();
            [r.cellTemperature.value, r.cellTemperature.timestamp] = obj.system.getCellTemperature();
            [r.pumpPower.value,       r.pumpPower.timestamp] = obj.system.getPumpPower();

            len = length(obj.record);
            if len == 0
                obj.record = r;
            else
                obj.record(len+1) = r;
            end
        end
        
        function obj = createTimer(obj, period)
            L=log4m.getLogger;
            if nargin == 1
                period = 10;
            end
            
            if isempty(obj.timerObj)
                obj.timerObj = timer('Name', 'MonitorTimer', 'ExecutionMode',  'fixedRate', 'Period', period, 'TimerFcn', @(tm, event) obj.getData() );
            else
                L.info('SystemMonitor::createTimer', 'Timer already exists.');
            end
        end
        
        function obj = start(obj)
            start(obj.timerObj);
        end
        
        function obj = stop(obj)
            stop(obj.timerObj);
        end
        
        function obj = setPeriod(obj, period)
            obj.stop();
            obj.timerObj.Period = period;
            obj.start();
        end
    end
end

